<script setup>
import { nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import utils from '@/utils/utils';
import { attachmentDownloadService } from '@/api/forumArticle';

// 接收父组件传递过来的文章信息
let props = defineProps({
  forumArticleAttachmentList: {
    type: Array,
    default: null
  }
})

// 下载附件
const downloadAttachment = async (fileId, fileName, bucketName, objectName) => {
  // let iframe = document.createElement("iframe")
  let res = await attachmentDownloadService({
    fileId,
    fileName,
    bucketName,
    objectName
  })
  console.log(res)

  try {

    const blob = new Blob([res.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')

    // 获取文件名（假设后端返回的filename=后面直接跟名称）
    const fileName = decodeURI(
      res.headers['content-disposition'].split('filename=')[1]
    )

    link.href = url
    link.download = fileName
    link.click() // 自动触发点击

    // 清理资源
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('下载失败:', error)
    alert('文件下载失败，请重试')
  }

}

</script>

<template>
  <!-- 附件信息 -->
  <div class="article-attachment" id="article-attachment">
    <div class="attachment-title">附件</div>
    <ul>
      <li class="attachment-item" v-for="item in forumArticleAttachmentList">
        <span class="iconfont icon-fujian1"></span>
        <span class="attachment-name">{{ item.fileName }}</span>
        <span class="attachment-size">{{ utils.sizeToStr(item.fileSize) }}</span>
        <span class="attachment-integral">需要<span style="margin: 0 3px;color: red;">{{ item.integral
        }}</span>积分</span>
        <span class="attachment-download-count">已下载 {{ item.downloadCount }} 次</span>
        <el-button type="success" size="small"
          @click="downloadAttachment(item.fileId, item.fileName, item.bucketName, item.objectName)">下载</el-button>
      </li>
    </ul>
  </div>
</template>

<style scoped>
.article-attachment {
  margin-top: 20px;
  background-color: #f2f3f5;
  background-color: #fff;
  padding: 20px;
  font-size: 14px;
  color: #555666;
  cursor: default;
}

.article-attachment .attachment-title {
  font-size: 20px;
  margin-bottom: 10px;
}

.article-attachment .attachment-item {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.article-attachment .attachment-item span {
  margin-right: 10px;
}

.article-attachment .attachment-item .icon-fujian1 {
  color: green;
}

.article-attachment .attachment-item .attachment-name {
  color: green;
  border-bottom: 1px solid green;
}
</style>